package com.atguigu.dga.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class ThreadDemo {


    public static void main(String[] args) {

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(20));

        Integer[]  nums={1,2,3,4,5};
        // 1  计算容器中每个数的平方  2 把计算后的结果加总
        List<Integer> newNumList=new ArrayList<>();  //现货列表
        long startTs = System.currentTimeMillis();
        List<CompletableFuture<Integer>> futureList=new ArrayList<>();//期货列表
        //1
        for (Integer num : nums) {
            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
                ///////////////需要异步///////////////
                Integer newNum = num * num;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                ///////////////需要异步///////////////
                return newNum;
            },threadPoolExecutor);

            futureList.add(completableFuture);
           // newNumList.add(newNum);
        }
        //期货兑换成现货
        newNumList = futureList.stream().map(future -> future.join()).collect(Collectors.toList());

        long endTs = System.currentTimeMillis();
        System.out.println("duration = " + (endTs-startTs));
        //2
        Integer total=0;
        for (Integer num : newNumList) {
            total+=num;
        }

        System.out.println("total = " + total);


    }
}
